
import tkinter as tk
import time
import urllib
from urllib import request
import mysql
from mysql import connector

class AuRMB:
    au_info = dict()
    def __init__(self):
        try:
            self._getdata()
        except:
            o = {
                'buy' : '0.0',
                'sell' : '0.0',
                'low' : '0.0',
                'max' : '0.0',
                'time' : None
            }
            self.au_info.update(o)

    def _getdata(self):
        url = 'http://m.sojex.cn/api.do?rtp=GetQuotesDetail&id=3'
        f = urllib.request.urlopen(url)
        data = f.read()
        data_dict = eval(data)
        self.au_info = data_dict.get('data').get('quotes')

    def get_daocursor(self):
        config = {
            'host' : 'localhost',
            'port' : '3306',
            'database' : 'econimic_data',
            'user' : 'root',
            'password' : '123456'
        }
        con = connector.connect(**config)
        return con.cursor()
    
    def get_au_info(self):
        return self.au_info
    
    def get_by_field(self,field):
        return self.au_info.get(field)
    
    def get_time_of_price(self):
        # todo: convert time format to yyyy-MM-dd HH:mm:ss
        return self.au_info.get('time')
    
    def get_bank_buy_price(self):
        return self.au_info.get('buy')
    
    def get_bank_sell_price(self):
        return self.au_info.get('sell')

def update_Au_price(label):
    def record(line):
        f = open('au_rmb.txt','a')
        f.write(line+'\n')
        f.close()
    def update():
        au = AuRMB()
        price = au.get_bank_sell_price()
        time = au.get_time_of_price()
        info = '%s Bank Sell: %s' % (time, str(price))
        label.config(text=info)
        label.after(1000*30,update)
        record(info)
    update()

root = tk.Tk()
root.title('gold price')
button_head_hidden = tk.Button(root,text='H',command=lambda:root.overrideredirect(True))
button_head_hidden.pack(side='left')
button_head_show = tk.Button(root,text='S',command=lambda:root.overrideredirect(False))
button_head_show.pack(side='left')
label = tk.Label(root, text='AuRMB')
label.pack(side='left')
button_shutdown = tk.Button(root,text='X',command=root.destroy)
button_shutdown.pack(side='left')
update_Au_price(label)
# root.overrideredirect(True)
root.wm_attributes('-topmost',1)
root.mainloop()